using Newtonsoft.Json;
using ReportToolAPI.Models;

namespace ReportToolAPI.Services
{
    /// <summary>
    /// 数据库配置文件管理服务
    /// </summary>
    public class DatabaseConfigService
    {
        private readonly string _configFilePath;
        private List<DatabaseConfig> _databases = new();
        private int _nextId = 1;
        private readonly object _lock = new();

        public DatabaseConfigService()
        {
            // 获取程序所在目录的上级目录（项目根目录）
            // 如果是在 bin/Debug/net6.0 运行，会找到项目根目录
            var currentDir = AppDomain.CurrentDomain.BaseDirectory;
            var projectRoot = currentDir;
            
            // 如果在 bin 目录下，向上找到项目根目录
            if (currentDir.Contains("bin"))
            {
                var binIndex = currentDir.IndexOf("bin");
                projectRoot = currentDir.Substring(0, binIndex);
            }
            
            _configFilePath = Path.Combine(projectRoot, "databases.json");
            Console.WriteLine($"✓ 配置文件路径: {_configFilePath}");
            
            LoadConfigs();
        }

        /// <summary>
        /// 从文件加载配置
        /// </summary>
        private void LoadConfigs()
        {
            try
            {
                if (File.Exists(_configFilePath))
                {
                    var json = File.ReadAllText(_configFilePath);
                    _databases = JsonConvert.DeserializeObject<List<DatabaseConfig>>(json) ?? new List<DatabaseConfig>();
                    
                    // 计算下一个 ID
                    if (_databases.Any())
                    {
                        _nextId = _databases.Max(d => d.Id) + 1;
                    }
                    
                    Console.WriteLine($"✓ 已加载 {_databases.Count} 个数据库配置");
                }
                else
                {
                    Console.WriteLine("✓ 配置文件不存在，将创建新文件");
                    SaveConfigs();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 加载配置文件失败: {ex.Message}");
                _databases = new List<DatabaseConfig>();
            }
        }

        /// <summary>
        /// 保存配置到文件
        /// </summary>
        private void SaveConfigs()
        {
            try
            {
                var json = JsonConvert.SerializeObject(_databases, Formatting.Indented);
                File.WriteAllText(_configFilePath, json);
                Console.WriteLine($"✓ 配置已保存到 {_configFilePath}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 保存配置文件失败: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 获取所有数据库配置
        /// </summary>
        public List<DatabaseConfig> GetAll()
        {
            lock (_lock)
            {
                return _databases.ToList();
            }
        }

        /// <summary>
        /// 根据 ID 获取配置
        /// </summary>
        public DatabaseConfig? GetById(int id)
        {
            lock (_lock)
            {
                return _databases.FirstOrDefault(d => d.Id == id);
            }
        }

        /// <summary>
        /// 添加数据库配置
        /// </summary>
        public DatabaseConfig Add(DatabaseConfig config)
        {
            lock (_lock)
            {
                config.Id = _nextId++;
                _databases.Add(config);
                SaveConfigs();
                return config;
            }
        }

        /// <summary>
        /// 更新数据库配置
        /// </summary>
        public bool Update(int id, DatabaseConfig config)
        {
            lock (_lock)
            {
                var existing = _databases.FirstOrDefault(d => d.Id == id);
                if (existing == null)
                    return false;

                existing.Index = config.Index;
                existing.Name = config.Name;
                existing.DatabaseName = config.DatabaseName;
                existing.Ip = config.Ip;
                existing.Port = config.Port;
                existing.Username = config.Username;
                existing.Password = config.Password;

                SaveConfigs();
                return true;
            }
        }

        /// <summary>
        /// 删除数据库配置
        /// </summary>
        public bool Delete(int id)
        {
            lock (_lock)
            {
                var config = _databases.FirstOrDefault(d => d.Id == id);
                if (config == null)
                    return false;

                _databases.Remove(config);
                SaveConfigs();
                return true;
            }
        }
    }
}

